import { request } from '../../request/index.js';
Page({
    data: {
        types: [{ name: '日常', state: false }, { name: '服饰', state: false }, { name: '学具', state: false }, { name: '其它', state: false }],
        sort: [{ name: '时间', state_F: true, state_S: false }, { name: '价格', state_F: false, state_S: false }],
        keywords: '',
        noramalData: [],
        leftList: [],
        rightList: [],
        NowPage: 0,//当前页数
        numList: 0,//当前list数量
        LeftH: 0,
        RightH: 0,
        isNull: false,
        nowScroll: 0,
    },

    onLoad: function (options) {
        let _this = this
        wx.showToast({
            title: '请稍等',
            icon: 'loading',
            duration: 2000,
            mask: true,
        })
        _this.setData({//重置所有状态
            types: [{ name: '日常', state: false }, { name: '服饰', state: false }, { name: '学具', state: false }, { name: '其它', state: false }],
            sort: [{ name: '时间', state_F: true, state_S: false }, { name: '价格', state_F: false, state_S: false }],
            keywords: '',
        })
        this.Search(1)
    }, onReady: function (options) {
        this.judgmentTopH()

    }, onPageScroll: function (e) {
        let animation = ''
        //快速切换的动画，随滚轴而动
        let animationA = wx.createAnimation({
            duration: 100,
            timingFunction: 'step-start',
            delay: 0,
        });
        //慢速切换的动画，用于隐藏和显现
        let animationB = wx.createAnimation({
            duration: 100,
            timingFunction: 'linear',
            delay: 0,
        });
        let animationC = wx.createAnimation({
            duration: 400,
            timingFunction: 'linear',
            delay: 0,
        });
        let stateTop
        if (e.scrollTop > this.data.nowScroll) {//下滑
            if (e.scrollTop >= this.data.totalTop) {
                animationB.translateY('-200rpx').step();
                animation = animationB
                animationC.opacity(1).step();
            } else {
                animationA.translateY(-e.scrollTop).step();
                animation = animationA
                animationC.opacity(0).step();
            }
            stateTop = 0
        } else {
            if (e.scrollTop >= this.data.totalTop) {//上滑
                animationB.translateY(0).step();
                animation = animationB
                animationC.opacity(1).step();
                stateTop = 1
            } else {
                if (this.data.stateTop != 1) {
                    animationA.translateY(-e.scrollTop).step();
                    animation = animationA
                    animationC.opacity(0).step();
                    stateTop = 0
                } else {
                    animationC.opacity(0).step();
                    stateTop = 1
                }
            }
        }
        this.setData({
            nowScroll: e.scrollTop,
            topAnimation: animation,
            BottomAnimation: animationC,
            stateTop: stateTop
        })

    }, onPullDownRefresh() {//下拉
        //做些什么...
        this.onLoad()
        wx.stopPullDownRefresh()//得到结果后关掉刷新动画
    }, onReachBottom() {//上拉
        let Page = this.data.NowPage + 1
        this.Search(Page)
    },

    toTop(e) {
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
        });
    },

    getInputValue(e) {//获取模糊查询关键字    
        let key = e.detail.value
        key = key.trim()
        this.setData({
            keywords: key
        })
    },
    toSearch() {//点击搜索
        this.Search(1)
    },
    select_ord(e) {//选择排序方式
        function setZ(a) {
            a[0].state_F = false
            a[0].state_S = false
            a[1].state_F = false
            a[1].state_S = false
        }
        var position = e.currentTarget.dataset.position
        let sort = this.data.sort
        let _sort = []
        for (let i = 0; i < sort.length; i++) {
            _sort[i] = { ...sort[i] }
        }
        if (!sort[position].state_F) {
            setZ(sort)
            sort[position].state_F = true
        } else {
            setZ(sort)
            sort[position].state_S = true 
        }

        this.Search(1).then(data => {
            if (data == 1)
                this.setData({
                    sort: sort
                })
            else {
                this.setData({
                    sort: _sort
                })
                wx.showToast({
                    title: '点击太频繁',
                    icon: 'error',
                    duration: 1000,
                    mask: false,
                })
            }
        })
    },
    select_type(e) {//选择类型
        var position = e.currentTarget.dataset.position
        let types = this.data.types
        let _types = []
        for (let i = 0; i < types.length; i++) {
            _types[i] = { ...types[i] }
        }
        for (let i = 0; i < types.length; i++)
            types[i].state = false
        types[position].state = true
        console.log(this.data.types);
        console.log(_types);
        this.Search(1).then(data => {
            console.log(data)
            if (data === 1)
                this.setData({
                    types: types
                })
            else {
                this.setData({
                    types: _types
                })
                wx.showToast({
                    title: '点击太频繁',
                    icon: 'error',
                    duration: 1000,
                    mask: false,
                })
            }
        })

    },

    judgmentData() {// 判断是否有数据
        if (this.data.noramalData.length == 0) {
            this.setData({
                isNull: true
            })
        } else {
            this.judgmentList()
            this.setData({
                isNull: false
            })
        }
    },
    async judgmentList() {// 判断左右list分别装入哪些数据
        const _this = this
        var allData = this.data.noramalData;
        var leftData = this.data.leftList;
        var rightData = this.data.rightList;
        var num = this.data.numList + allData.length
        function judgmentH(className) {
            return new Promise((resolve, reject) => {
                let query = wx.createSelectorQuery();
                query.select(className).boundingClientRect(res => {
                    resolve(res.height)
                }).exec()
            })
        }
        for (let i = _this.data.numList; i < num; i++) {
            let LH = await judgmentH('.leftList')
            let RH = await judgmentH('.rightList')
            // console.log(LH + " " + RH)
            if (LH <= RH) {//判断左右两侧当前的累计高度，来确定item应该放置在左边还是右边
                leftData.push(allData[i]);
            } else {
                rightData.push(allData[i]);
            }
            _this.setData({
                leftList: leftData,
                rightList: rightData,
            })

        }

    },
    async judgmentTopH() {// 判断顶部高度
        function judgmentH(className) {
            return new Promise((resolve, reject) => {
                let query = wx.createSelectorQuery();
                query.select(className).boundingClientRect(res => {
                    resolve(res.height)
                }).exec()
            })
        }
        let totalTop = await judgmentH('.search_top')
        totalTop += await judgmentH('.search_types')
        this.setData({
            totalTop: totalTop
        })
    },
    async Search(curPage) {//查询接口
        let _this = this
        let { keywords, types, sort } = this.data
        let _type = 0
        let _sort = 0;
        let url;
        for (let i = 0; i < types.length; i++) {
            if (types[i].state)
                _type = i + 1;
        }
        for (let i = 0; i < sort.length; i++) {
            if (sort[i].state_F)
                _sort = i * 2 + 1;
            if (sort[i].state_S)
                _sort = i * 2 + 2;
        }
        if (!keywords || keywords == null) {
            keywords = 'kmtzsc'
        }
        url = `/commodity/get/${keywords}/${_type}/${_sort}/${curPage}`
        const { data } = await request({
            url: url
        })
        if (data.state === 1) {
            var _noramalData = data.data.commodities
            let p = 1;//重置当前页面需要的页数，有数据则是一页重置，无数据则是零页重置
            if (_noramalData.length == 0) {
                --curPage;
                p = 0;
            } else {
                for (var i = 0; i < _noramalData.length; i++) {
                    var img = _noramalData[i].imgs
                    var imgs = []
                    if (img) {
                        imgs = img.split("|")//分割图片数组
                        imgs = imgs.slice(0, imgs.length - 1)//去除末尾空值
                    }
                    _noramalData[i].imgs = imgs
                }
            }
            if (curPage == p) {
                _this.setData({
                    leftList: [],
                    rightList: [],
                    noramalData: _noramalData,
                    NowPage: curPage,
                })
            } else {
                _this.setData({
                    noramalData: _noramalData,
                    NowPage: curPage,
                })
            }
        } else {
            wx.showToast({
                title: '访问太频繁',
                icon: 'error',
                duration: 2000,
                mask: false,
            })
            if (curPage == 0) {
                _this.setData({
                    leftList: [],
                    rightList: [],
                    noramalData: [],
                })
            } else {
                _this.setData({
                    noramalData: [],
                })
            }
        }
        _this.judgmentData()
        console.log(data.state)
        return data.state
    },

    toDetailPage(e) {//前往商品详细页面
        let position = e.currentTarget.dataset.position
        let id = e.currentTarget.dataset.id
        let nextData = {}
        let list = []
        if (position == 0) {
            list = this.data.leftList
        } else {
            list = this.data.rightList
        }
        for (let i = 0; i < list.length; i++) {
            if (list[i].id == id) {
                nextData = list[i]
            }
        }
        let data = JSON.stringify(nextData)
        wx.navigateTo({
            url: `/pages/FMDetailPage/FMDetailPage?nextData=${data}`
        })
    },
})